<template>
  <div>
    <el-form
      ref="ruleFormRef"
      :model="ruleForm"
      status-icon
      :rules="rules"
      label-width="120px"
      class="demo-ruleForm"
    >
      <el-form-item label="用户名" prop="username">
        <el-input v-model="ruleForm.username" autocomplete="off" />
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input v-model="ruleForm.password" type="password" />
      </el-form-item>
      <el-form-item label="角色" prop="role">
        <el-select v-model="ruleForm.role">
          <el-option
            v-for="item in roleOption"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="头像" prop="avatar">
        <Upload :avatar="ruleForm.avatar" @change="handleChange" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitForm(ruleFormRef)"
          >添加用户</el-button
        >
      </el-form-item>
    </el-form>
  </div>
</template>
<script setup>
import { reactive, ref,  } from 'vue';
import { ElMessage } from 'element-plus';
import uploadFun from '@/util/uploadFun';
import Upload from '@/components/upload/Upload.vue';
import { useRouter } from 'vue-router';

const router = useRouter();
const ruleFormRef = ref();
const roleOption = [
  { label: '管理员', value: 1 },
  { label: '编辑', value: 2 },
];
const ruleForm = reactive({
  username: '',
  password: '',
  avatar: '',
  role: null, //1管理员2编辑
  file: null, // 上传的原生文件对象
  sex: 0,
});
const rules = reactive({
  username: [{ required: true, message: '请输入名字', trigger: 'blur' }],
  password: [{ required: true, message: '请输入密码', trigger: 'blur' }],
  role: [{ required: true, message: '请选择角色', trigger: 'blur' }],
  avatar: [{ required: true, message: '请选择头像', trigger: 'change' }],
});
const handleChange = (file) => {
  ruleForm.avatar = URL.createObjectURL(file);
  ruleForm.file = file;
};
const submitForm = () => {
  ruleFormRef.value.validate(async (valid) => {
    if (valid) {
      const res = await uploadFun('/adminApi/user/add', ruleForm);
      if (res.code === 200) {
        ElMessage({
          message: res.msg,
          type: 'success',
        });
        router.push('/user-manage/user-list');
      }
    }
  });
};
</script>
<style lang="scss" scoped></style>
